const Router = require('koa-router')

const {success} = require('../../lib/helper')

const nodemailer = require('nodemailer')

const router = new Router({
    prefix: '/v1/code'
})



// 创建一个 nodemailer transporter
const transporter = nodemailer.createTransport({
    host: 'smtp.163.com',
    port: 465,
    secure: true,
    auth: {
        user: '15621878026@163.com',
        pass: 'SMWZPJTQFRVKZZDE'
    }
})


let code = '';
let expiryTime = 0;


// 生成随机验证码
function generateCode() {
    code = Math.floor(1000 + Math.random() * 9000).toString();
    expiryTime = Date.now() + 600000; // 设置验证码有效期为10分钟
}

// 发送邮件的接口
router.post('/sendEmail', async (ctx) => {
    const { email } = ctx.request.body;

    // 生成验证码
    generateCode();

    // 设置邮件内容
    const mailOptions = {
        from: '15621878026@163.com',
        to: email,
        subject: '预约系统验证码',
        text: `您的验证码是: ${code}`
    }

    // 将 transporter.sendMail 的回调转换为 Promise
    const sendMailPromise = new Promise((resolve, reject) => {
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                reject(error);
            } else {
                resolve(info);
            }
        });
    })

    try {
        // 等待邮件发送完成
        const info = await sendMailPromise;
        console.log('Email sent:', info);
        ctx.body = { success: true, message: 'Verification code sent successfully' };
    } catch (error) {
        console.error('Error sending email:', error);
        ctx.body = { success: false, message: 'Failed to send verification code' };
    }
})

// 验证验证码的接口
router.post('/verifyCode', async (ctx) => {
    const { codeToVerify } = ctx.request.body;

    if (Date.now() > expiryTime) {
        ctx.body = { success: false, message: 'Verification code expired' };
    } else if (codeToVerify === code) {
        ctx.body = { success: true, message: 'Verification code is correct' };
    } else {
        ctx.body = { success: false, message: 'Incorrect verification code' };
    }
})



// 假设你已经有了 transporter 的配置和初始化

router.post('/sendSuccessEmail', async (ctx) => {
    const { email } = ctx.request.body;

    // 检查 email 是否有效，这里只是简单示例
    if (!email || !email.includes('@')) {
        ctx.body = { success: false, message: 'Invalid email address' };
        return;
    }

    // 设置邮件内容
    const mailOptions = {
        from: '15621878026@163.com',
        to: email,
        subject: '申请审核通过通知',
        text: '您的申请已被管理员审核通过，请在您申请的时间内去使用设备，也可登录网站查看预约反馈详情'
    }

    // 将 transporter.sendMail 的回调转换为 Promise
    const sendMailPromise = new Promise((resolve, reject) => {
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                reject(error);
            } else {
                resolve(info);
            }
        });
    })

    try {
        // 等待邮件发送完成
        const info = await sendMailPromise;
        console.log('Email sent:', info);
        ctx.body = { success: true, message: 'Approval notification sent successfully' };
    } catch (error) {
        console.error('Error sending email:', error);
        ctx.body = { success: false, message: 'Failed to send approval notification' };
    }
})


router.post('/sendFailEmail', async (ctx) => {
    const { email } = ctx.request.body;

    // 检查 email 是否有效，这里只是简单示例
    if (!email || !email.includes('@')) {
        ctx.body = { success: false, message: 'Invalid email address' };
        return;
    }

    // 设置邮件内容
    const mailOptions = {
        from: '15621878026@163.com',
        to: email,
        subject: '申请审核不通过通知',
        text: '您的申请已被管理员审核拒绝，您可登录网站查看预约反馈详情'
    }

    // 将 transporter.sendMail 的回调转换为 Promise
    const sendMailPromise = new Promise((resolve, reject) => {
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                reject(error);
            } else {
                resolve(info);
            }
        });
    })

    try {
        // 等待邮件发送完成
        const info = await sendMailPromise;
        console.log('Email sent:', info);
        ctx.body = { success: true, message: 'Approval notification sent successfully' };
    } catch (error) {
        console.error('Error sending email:', error);
        ctx.body = { success: false, message: 'Failed to send approval notification' };
    }
});


// 注意：
// 1. 我将路由从 '/sendEmail' 改为了 '/sendApprovalEmail'，以更清晰地反映其用途。
// 2. 请确保你有权使用 'noreply@yourdomain.com' 作为发件人邮箱，并替换为你的实际邮箱。
// 3. 检查并配置你的 transporter 以确保它能正确发送邮件。



module.exports = router